package com.webchat.act.service;


import com.webchat.act.repository.entity.ResourceBehaviorEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;


/**
 * 双向（支持取消操作）互动服务
 */
@Service
public class TwoWayResourceBehaviorService extends AbstractResourceBehaviorService {


    private static final String BEHAVIOR_ERROR_MSG = "%s失败";
    private static final String CANCEL_BEHAVIOR_ERROR_MSG = "取消%s失败";

    @Override
    protected boolean doBehavior(String userId, String resourceType, Long resourceId) {

        boolean isBehavior = this.isBehavior(userId, resourceType, resourceId);
        Assert.isTrue(!isBehavior, String.format(BEHAVIOR_ERROR_MSG, super.behaviorTypeName));
        ResourceBehaviorEntity resourceBehavior = new ResourceBehaviorEntity();
        resourceBehavior.setUserId(userId);
        resourceBehavior.setBehaviorType(super.behaviorType);
        resourceBehavior.setResourceType(resourceType);
        resourceBehavior.setResourceIndex(resourceId);
        resourceBehavior.setStatus(true);
        super.resourceBehaviorDAO.save(resourceBehavior);
        return false;
    }

    @Override
    protected boolean doCancelBehavior(String userId, String resourceType, Long resourceId) {

        boolean isBehavior = this.isBehavior(userId, resourceType, resourceId);
        Assert.isTrue(isBehavior, String.format(CANCEL_BEHAVIOR_ERROR_MSG, super.behaviorTypeName));

        ResourceBehaviorEntity resourceBehavior =
                resourceBehaviorDAO.findByUserIdAndBehaviorTypeAndResourceTypeAndResourceIndexAndStatusTrue(
                userId, super.behaviorType, resourceType, resourceId);
        Assert.notNull(resourceBehavior, String.format(CANCEL_BEHAVIOR_ERROR_MSG, super.behaviorTypeName));
        // 互动已取消
        resourceBehavior.setStatus(false);
        super.resourceBehaviorDAO.save(resourceBehavior);
        return true;
    }
}
